import { useEffect, useRef } from "react";
import { useLocation } from "react-router-dom";
import { findRouteMatch, LoadMicroApp } from "./utils";
import userInfoStore from "@/store/userinfo";

const LoadApp = ({ children }: { children: React.ReactNode }) => {
  const location = useLocation();
  const lastMicroKeyRef = useRef<string | null>(null); // 本地缓存

  useEffect(() => {
    if (!userInfoStore.routes || userInfoStore.routes.length === 0) return;

    const currentRoute = findRouteMatch(
      userInfoStore.routes,
      location.pathname
    );
    const newKey = currentRoute?.mircoKey;

    if (newKey && lastMicroKeyRef.current !== newKey) {
      LoadMicroApp(newKey);
      lastMicroKeyRef.current = newKey;
    } else if (!newKey) {
      console.warn("未找到对应的 microKey", location.pathname);
    }
  }, [location, userInfoStore.routes]);

  return <>{children}</>;
};

export default LoadApp;
